﻿#include "UpdateWorker.h"
#include <QUrlQuery>
#include <QNetworkReply>
#include <QHttpMultiPart>
#include <QBuffer>
#include <QApplication>
#include <QFileInfo>
#include <QDebug>
#include <QDir>


UpdateWorker::UpdateWorker(QObject *parent)
    : QObject(parent)
{
    downloadFolder = QString("%1/%2/").arg(QApplication::applicationDirPath(), DOWNLOAD_FOLDER);
    QDir dir;
    if(!dir.exists(downloadFolder)){
        dir.mkpath(downloadFolder);
    }
}
UpdateWorker::~UpdateWorker()
{
    mNetWork->deleteLater();
}

void UpdateWorker::onInit()
{
    mNetWork = new QNetworkAccessManager(this);
}
void UpdateWorker::onQuit()
{
    deleteLater();
}

void UpdateWorker::onUpdateFile(QString url, QString dstPath)
{

    auto basename = QFileInfo(dstPath).fileName();
    if(basename.isEmpty())
        return;

    basename = downloadFolder + basename;
    //定义下载后的文件路径
    QString tempFile = basename + DOWNLOAD_FILE_SUFFIX;
    //delete tmp file before download
    QFile::remove(tempFile);
    QNetworkRequest request(url);
    // 设置 HTTP 请求头
    request.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0");
    request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
    request.setRawHeader("Accept-Encoding", "gzip, deflate, br, zstd");
    request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
    request.setRawHeader("Connection", "keep-alive");
    request.setRawHeader("Cookie", "1iSB7et3MIV-2RqBD_user_uuid=$3450004411791754854; yhj4j94daea02d5ea4f6d80b74f1507eddb42=1iSB7et3MIV-2RqBD; 1iSB7et3MIW-2RqBD_user_uuid=$3450004411800946901; _zcsr_tmp=bac83ae4-de0d-4432-b548-57297be601f0; drscc=bac83ae4-de0d-4432-b548-57297be601f0; 1iSB7et3MIY-2RqBD_user_uuid=$3450004411845325965; 1iSB7et3MIZ-2RqBD_user_uuid=$3450004411958546901; yhj4j0134f4cf67c647cfa5356970d4e31913=1iSB7et3MIZ-2RqBD");
    request.setRawHeader("Referer", "https://workdrive.zohopublic.com.cn/");
    request.setRawHeader("Sec-CH-UA", "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\", \"Microsoft Edge\";v=\"132\"");
    request.setRawHeader("Sec-CH-UA-Mobile", "?0");
    request.setRawHeader("Sec-CH-UA-Platform", "\"Windows\"");
    request.setRawHeader("Sec-Fetch-Dest", "iframe");
    request.setRawHeader("Sec-Fetch-Mode", "navigate");
    request.setRawHeader("Sec-Fetch-Site", "same-site");
    request.setRawHeader("Sec-Fetch-User", "?1");
    request.setRawHeader("Upgrade-Insecure-Requests", "1");
    // 设置必要的请求头
    auto reply = mNetWork->get(request);

    connect(reply, &QNetworkReply::downloadProgress, this, &UpdateWorker::sigDownloadProgress);

    connect(reply, &QNetworkReply::readyRead, this, [tempFile, reply]{
        QFile file(tempFile);
        if (file.open(QIODevice::WriteOnly | QIODevice::Append)){
            file.write(reply->readAll());
        }
        file.close();
    });

    connect(reply, &QNetworkReply::finished, this, [reply, tempFile, dstPath, this] {
        QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        qDebug() << "download of network return code " << status_code.toInt();
        bool success = false;
        if (reply->error() == QNetworkReply::NoError){
            success = updateFile(tempFile, dstPath);
        } else {
            qDebug() << "Download of " << tempFile << " failed:" << reply->errorString();
        }
        reply->deleteLater();
        emit sigDownloadFinished(dstPath, success);
    });
}
bool UpdateWorker::updateFile(QString src, QString dst)
{
    QFileInfo fileInfo(src);
    QFile fileOld(dst);
    QFile fileTmp(src);
    QFile fileBck(dst + "-bck");
    if(fileInfo.exists() && fileInfo.size() > 0){
        fileBck.remove();
        if(!fileOld.rename(dst + "-bck")){
            qDebug()<< "Failed to rename old file!";
            return false;
        }
        if(!fileTmp.rename(dst)){
            qDebug()<< "Failed to rename tmp file!";
            return false;
        }
    }else{
        return false;
    }
    return true;
}


